<template>
<div class="main detailView">
    <div class="header">
      <!-- 头部导航 -->
       <van-nav-bar title="嗨购商城" left-text="返回" left-arrow>
            <template #right>
                <van-popover v-model="showPopover" trigger="click" :actions="actions" placement="bottom-end" theme="dark" @select="onSelect">
                    <template #reference>
                        <van-icon name="ellipsis" size="24" color="black" />
                    </template>
                </van-popover>
            </template>
            <div>aaaa</div>
            <template #left>
                <van-icon name="arrow-left"  @click="$router.back()" size="24" color="black" ></van-icon>
            </template>
        </van-nav-bar>
        <!-- 分享模块 -->
        <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
        />
    </div>
    <div class="content">
      <!-- 轮播图 -->
        <div class="banner">
        <van-swipe lazy-render  :show-indicators="false" @change="onChange" :initial-swipe="imgindex">
            <van-swipe-item v-for="(image, index) in banners" :key="index">
                <img :src="image" @click="preview" />
            </van-swipe-item>
        </van-swipe>
        <div class="page">
            {{index}}/{{banners.length}}
        </div>
    </div>
    <!-- 产品信息栏 -->
    <div class="merchandise">
        <div class="proPrice">
            <div class="price">
                <i>￥</i>{{ originprice.toFixed(2) }}
            </div>
            <div class="sales">
                已售{{ sales | salesFilter }}+件
            </div>
        </div>
        <div class="proTitle">
            <div class="title van-multi-ellipsis--l2">
                {{ desc }}
            </div>
            <div class="collect">
                <van-icon name="star-o" size="18" /><span>收藏</span>
            </div>
        </div>
        <div class="ranking">
            <van-icon name="medal" color="#e54847" />
            <div class="category">
                {{ category }}热销榜第{{ isrecommend }}名
                <van-icon name="arrow" size="12" />
            </div>
        </div>
    </div>
    <!-- 物流信息 -->
    <div class="logistics">
    </div>
    </div>
    <!-- 底部购买和加入购物车 -->
    <div class="footer">
        <van-goods-action>
            <van-goods-action-icon icon="chat-o" @click="service" text="客服" />
            <van-badge :content="cartNum">
              <van-goods-action-icon icon="cart-o" @click="$router.push('/cart')" text="购物车" />
            </van-badge>
            <van-goods-action-icon icon="shop-o" text="店铺" />
            <van-goods-action-button type="warning" @click="isshow = true" text="加入购物车" />
            <van-goods-action-button type="danger" @click="isshow = true" text="立即购买" />
        </van-goods-action>
        </div>
            <van-sku
          v-model="isshow"
          :sku="sku"
          :goods-id="proid"
          :quota="quota"
          :goods="sku.goods_info"
          :quota-used="quota_used"
          :hide-stock="sku.hide_stock"
          @buy-clicked="onBuyClicked"
          @add-cart="onAddCartClicked"
        />
    </div>
    </template>
<style lang="stylus">
.detailView .van-badge--fixed
      top .125rem
      right .5rem
</style>
<style lang="stylus" scoped>
.main
    height 100%
    background-color rgb(246,246,246)
    display flex
    flex-direction column
    overflow auto
    .content
        flex 1
        overflow auto
.banner img
    width 100%
.merchandise
    border-radius .625rem
    margin .625rem
    background-color white
    padding .625rem
    .proPrice
        display flex
        align-items center
        justify-content space-between
        .price
            font-size 1.5rem
            color #e54847
            font-weight bold
            i
                font-size: 1rem
                font-style normal
                font-weight 400
        .sales
            font-size .875rem
            color #555
    .proTitle
        display flex
        align-items center
        justify-content space-between
        border-bottom 1px solid #ccc
        padding .625rem 0
        .title
            flex 1
            color block
            font-size 1rem
            font-weight 600
        .collect
            width 2.375rem
            height 2.375rem
            font-size .875rem
            color #555
            display flex
            flex-direction column
            justify-content space-between
            align-items center
    .ranking
        display flex
        align-items center
        padding .625rem 0
        .badge
            // width 1.25rem
        .category
            padding-left .3125rem
            flex 1
            display flex
            justify-content space-between
            align-items center
            font-size .875rem
            color #555
.footer
    height 3.125rem
    background-color red
.banner
    position relative
.page
    background-color #00000033
    color #fff
    border-radius .9375rem 0 0 .9375rem
    position absolute
    bottom 1.25rem
    right 0
    font-size .875rem
    padding .125rem .625rem
</style>

<script>
import { getDetail, getadd, getList, getSelectAll, getAaddOrder } from '@/api/Detail'
import Vue from 'vue'
import { Swipe, SwipeItem, ImagePreview, GoodsAction, GoodsActionIcon, GoodsActionButton, NavBar, Popover, ShareSheet, Sku, Toast, Badge } from 'vant'
Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(ImagePreview)
Vue.use(GoodsAction)
Vue.use(GoodsActionIcon)
Vue.use(GoodsActionButton)
Vue.use(NavBar)
Vue.use(Popover)
Vue.use(ShareSheet)
Vue.use(Sku)
Vue.use(Toast)
Vue.use(Badge)
export default {
  filters: {
    salesFilter (val) {
      if (val > 10000) {
        return parseInt(val / 10000) + '万'
      } else {
        return val
      }
    }
  },
  data () {
    return {
      show: false,
      isshow: false,
      sku: {},
      goods_id: '946755',
      quota: 0, // 限购数量
      quota_used: 0, // 已经购买过的数量
      //   产品图片
      banners: [],
      //   品牌
      brand: '',
      //   产品类目
      category: '',
      //   产品介绍
      desc: '',
      //   折扣
      discount: 0,
      //   推荐榜排名
      isrecommend: 0,
      //   销量排名
      issale: 0,
      //   是否是秒杀产品
      isseckill: '',
      //   原价
      originprice: 0,
      //   产品id
      proid: '',
      //   产品名称
      proname: '',
      //   销量
      sales: 0,
      // 购物车数量
      cartNum: 0,
      // 用户id
      userid: '',
      //   库存数量
      stock: 0,
      orderState: [],
      showPopover: false,
      actions: [{ text: '首页', icon: 'home-o', index: 0 }, { text: '分类搜素', icon: 'apps-o', index: 1 }, { text: '我的嗨购', icon: 'user-o', index: 2 }, { text: '浏览记录', icon: 'clock-o', index: 3 }, { text: '我的关注', icon: 'like-o', index: 4 }, { text: '分享', icon: 'guide-o', index: 5 }],
      index: 1,
      imgindex: 0,
      startPosition: 0,
      showShare: false,
      options: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '朋友圈', icon: 'wechat-moments' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' }
        ],
        [
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
          { name: '小程序码', icon: 'weapp-qrcode' }
        ]
      ]
    }
  },
  methods: {
    preview () {
      ImagePreview({
        images: this.banners,
        startPosition: this.startPosition,
        onChange: this.onChangeimg,
        onClose: this.onClose
      })
    },
    onChange (index) {
      this.index = index + 1
      this.startPosition = index
    },
    onChangeimg (index) {
      this.imgindex = index
      this.index = index + 1
    },
    onClose (val) {
      this.imgindex = val.index
    },
    // 下拉选择列表
    onSelect (action) {
      switch (action.index) {
        case 0:
          this.$router.push('/home')
          break
        case 1:
          this.$router.push('/kind')
          break
        case 2:
          this.$router.push('/user')
          break
        case 3:
          console.log('我是浏览记录模块')
          break
        case 4:
          console.log('我是关注模块')
          break
        case 5:
          console.log('我是分享模块')
          this.showShare = true
          break
      }
    },
    // 购买事件
    onBuyClicked (state) {
      // 先将现有购物车商品的状态全部改成false
      getSelectAll({ userid: this.userid, type: false }).then((res) => {
        if (res.code === '200') {
          // 将当前商品加入购物车
          getadd({ userid: this.userid, proid: state.goodsId, num: state.selectedNum }).then((res) => {
            if (res.code === '200') {
              // 加购成功之后新建订单
              getAaddOrder({ userid: this.userid }).then((res) => {
                if (res.code === '200') {
                  this.orderState.unshift({ key: res.time, isflag: false, userid: this.userid })
                  // 更新全局状态中的订单状态
                  this.$store.commit('changeOrder', this.orderState)
                  // 将订单状态存储到本地存储
                  localStorage.setItem('orderState', JSON.stringify(this.orderState))
                  this.$router.push({ name: 'order', params: { timeId: res.time } })
                }
              })
              this.setCartNum()
            } else {
              Toast.fail('系统错误')
            }
            this.isshow = false
          })
        }
      })
    },
    // 加入购物车事件
    onAddCartClicked (state) {
      getadd({ userid: this.userid, proid: state.goodsId, num: state.selectedNum }).then((res) => {
        if (res.code === '200') {
          this.setCartNum()
          Toast.success('加购成功')
        } else {
          Toast.fail('系统错误')
        }
        this.isshow = false
      })
    },
    // 启动美洽客服
    service () {
      window._MEIQIA('showPanel')
    },
    // 计算当前购物车数量
    setCartNum () {
      getList({ userid: this.userid }).then((res) => {
        if (res.code === '200') {
          this.cartNum = res.data.length
        }
      })
    }
  },
  mounted () {
    // 获取订单状态
    this.orderState = this.$store.state.orderState ? this.$store.state.orderState : []
    // 获取当前产品id
    const proid = this.$route.params.id
    // 获取当前账号用户id
    this.userid = this.$store.state.userId ? this.$store.state.userId : false
    if (this.userid) {
      this.setCartNum()
    } else {
      this.cartNum = 0
    }
    // 获取当前商品信息
    getDetail(proid).then((res) => {
      const data = res.data
      this.goods = data
      this.banners = data.banners[0].split(',')
      this.brand = data.brand
      this.category = data.category
      this.desc = data.desc
      this.discount = data.discount
      this.isrecommend = data.isrecommend > 0 ? data.isrecommend : 1
      this.issale = data.issale
      this.isseckill = data.isseckill
      this.originprice = data.originprice
      this.proid = data.proid
      this.proname = data.proname
      this.sales = data.sales
      this.stock = data.stock
      this.goods_id = data.proid
      // 创建商品信息
      this.sku = {
        tree: [{
          k: '颜色',
          k_id: '1',
          v: [
            {
              id: data.proid,
              name: '白色',
              imgUrl: data.img1
            }
          ],
          k_s: 's1'
        }],
        list: [{
          id: 2257,
          price: data.originprice * 100,
          discount: data.discount,
          s1: data.proid,
          stock_num: data.stock - this.quota_used, // 库存
          goods_id: data.proid
        }],
        price: data.originprice.toFixed(2),
        stock_num: data.stock, // 商品总库存
        none_sku: false, // 是否无规格商品
        hide_stock: false, // 是否隐藏剩余库存
        goods_info: {
          title: '测试商品A',
          picture: data.img1
        }
      }
    })
  }
}
</script>
